import os
import threading

from flask import request

from app.common.libs.authentication import auth
from app.models.logModel import LogDetailModel, LogModel
from tools import db
from utils.utils import get_conversion_ip


def save_log(response):
    """
    - 500时，日志将由flask自身logger.error触发记录
    - 200+、400+状态码时由该处记录
    """

    level = "INFO"
    if 500 <= response.status_code:
        return response
    elif 400 <= response.status_code < 500:
        level = "ERROR"

    # 忽略登录，验证码，日志接口本身日志记录
    if request.endpoint in (
        "image.get_image_code",
        "libs.login",
        "log_monitor.logs_monitoring_api",
    ):
        return response

    try:
        log_obj = LogModel(
            ip=get_conversion_ip(),
            url_path=request.path,
            method=request.method,
            status_code=response.status_code,
            pid=os.getpid(),
            thread_id=threading.get_ident(),
            level=level,
            operator_name=auth.current_user().username if auth.current_user() else None,
        )
        db.session.add(log_obj)
        db.session.flush()
        db.session.add(
            LogDetailModel(
                log_id=log_obj.id,
                headers={
                    key: val for key, val in request.headers.items() if key.istitle()
                },
                message=response.data,
            )
        )
        db.session.commit()
    except Exception as _:  # noqa
        db.session.rollback()
    return response
